package com.tbit.uqbike.client.util;

import com.alibaba.fastjson.JSONObject;
import com.tbit.uqbike.client.pojo.WeixinPayConfig;
import com.tbit.uqbike.client.pojo.refund.RefundPojo;
import com.tbit.uqbike.client.remote.WeixinPay;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.*;
import java.util.Map.Entry;

/**
 * 文件读取
 *
 * @author Leon
 * 2013-12-20 上午11:32:33
 */
@Slf4j
public class Text {
    /**
     * 读取单次退款文件
     */
    public static List<RefundPojo> readOne(String filePath) {
        List<RefundPojo> users = new ArrayList<RefundPojo>();
        try {
            String encoding = "UTF-8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    String[] strings = lineTxt.split(";");
                    RefundPojo refundPojo = new RefundPojo();
                    if (strings.length < 8) {
                        System.out.println("格式错误" + strings);
                    } else {
                        refundPojo.setUserId(Integer.valueOf(strings[0]));
                        refundPojo.setPhone(strings[1]);
                        refundPojo.setName(strings[2]);
                        refundPojo.setIdNO(strings[3]);
                        /**要退款的总金额,即用户余额*/
                        refundPojo.setMoney(Integer.valueOf(strings[4]));
                        /**订单金额*/
                        refundPojo.setAllMoney(Integer.valueOf(strings[5]));
                        refundPojo.setPayTime(strings[6]);
                        refundPojo.setOrderNO(strings[7]);
                        users.add(refundPojo);
                    }
                }
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            log.error(e.getMessage(), e);
        }
        return users;
    }


    public static Map<String, List<RefundPojo>> readMore(String filePath) {
        Map<String, List<RefundPojo>> map = new HashMap<>();
        try {
            String encoding = "UTF-8";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    String[] strings = lineTxt.split(";");

                    if (strings.length < 2) {
                        System.out.println("格式错误" + strings);
                    } else {
                        List<RefundPojo> users;
                        if (map.get(strings[0]) == null) {
                            users = new ArrayList<RefundPojo>();
                        } else {
                            users = map.get(strings[0]);
                        }
                        RefundPojo refundPojo = new RefundPojo();
                        refundPojo.setUserId(Integer.valueOf(strings[0]));
                        refundPojo.setPhone(strings[1]);
                        refundPojo.setName(strings[2]);
                        refundPojo.setIdNO(strings[3]);
                        /**要退款的总金额,即用户余额*/
                        refundPojo.setMoney(Integer.valueOf(strings[4]));
                        /**订单金额*/
                        refundPojo.setAllMoney(Integer.valueOf(strings[5]));
                        refundPojo.setPayTime(strings[6]);
                        refundPojo.setOrderNO(strings[7]);
                        users.add(refundPojo);
                        map.put(strings[0], users);
                    }
                }
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            log.error(e.getMessage(), e);
        }
        return map;
    }

    public static boolean cash(Integer money, Integer allMoney, String orderNO) {
        WeixinPayConfig weixinPayConfig = new WeixinPayConfig();
        weixinPayConfig.setAppId("wxd1e516a01af2cb9c");
        weixinPayConfig.setSecret("f41d69671770354646e4c00fd7808334");
        weixinPayConfig.setPartnerkey("yniu3DieSFLPITq2Hx10NTOhawFdSIMI");
        weixinPayConfig.setAccountId(100008);
        weixinPayConfig.setPartner("1602876041");
        weixinPayConfig.setType(2);
        String refundNO = WeixinPayUtil.getReturnNonceStr();
        boolean b = WeixinPay.returnMoney(weixinPayConfig, orderNO, refundNO, money.toString(), allMoney.toString(),false);
        System.out.println(b);
        return b;
    }

    public static boolean upMoney(String userId, String money) {
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("userId", userId));
        params.add(new BasicNameValuePair("money", money));
        params.add(new BasicNameValuePair("remark", "停运人工退款"));
        params.add(new BasicNameValuePair("operaPsw", "QWERTYUIOP"));
        params.add(new BasicNameValuePair("token", "1bbfdf1f-ebcd-4ac2-a728-6c8b70b966ea"));
        String json = HttpClientUtils
                .httpPost("http://admin2.uqbike.cn/user/recharge.do", null, params);
        System.out.println(json);
        JSONObject jsonObject = JSONObject.parseObject(json);
        String data = jsonObject.getString("ret");
        System.out.println(data);
        if (data.equals("1")) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {

        Map<String, List<RefundPojo>> map = readMore("C:\\Users\\Administrator\\Desktop\\2.txt");
        System.out.println(map);
        Iterator<Entry<String, List<RefundPojo>>> iterator = map.entrySet().iterator();
        int i = 0;
        while (iterator.hasNext()) {

            Entry<String, List<RefundPojo>> entry = iterator.next();
            String key = entry.getKey();
            List<RefundPojo> list = entry.getValue();
            /**获取用户退款金额*/
            Integer money = list.get(0).getMoney();
            System.out.println("id=" + key + "用户退款总金额=" + money);
            for (RefundPojo r : list) {
                if (money > 0) {
                    System.out.println(r);
                    /**最后订单金额大于余额*/
                    if (r.getAllMoney() >= money) {
                        //boolean b=true;
                        boolean b = cash(money, r.getAllMoney(), r.getOrderNO());
                        if (b) {
                            System.out.println("退款成功，退款金额=" + money + ",总退款金额=" + money + ",订单金额=" + r.getAllMoney());
                            money = 0;
                        } else {
                            money = 0;
                            break;
                        }

                    } else {
                        //boolean b=true;
                        boolean b = cash(r.getAllMoney(), r.getAllMoney(), r.getOrderNO());
                        if (b) {
                            System.out.println("退款成功，退款金额=" + r.getAllMoney() + ",总退款金额=" + money + ",订单金额=" + r.getAllMoney());
                            money = money - r.getAllMoney();
                        } else {
                            money = 0;
                            break;
                        }

                    }
                }
            }
            //boolean b=true;
            boolean b = upMoney(key, String.valueOf(-list.get(0).getMoney()));
            if (!b) {
                System.out.println(key + "清除金额失败");
            }
            i++;
        }
        System.out.println("退款总笔数" + i);

        /**单笔退款*/
		/*List<RefundPojo> machineNOs=readOne("C:\\Users\\Administrator\\Desktop\\4.txt");
		System.out.println(machineNOs.size());
		for(RefundPojo refundPojo:machineNOs){
			//System.out.println(refundPojo);
			//boolean b=true;
			System.out.println(refundPojo.getUserId());
			boolean b= cash(refundPojo.getMoney(),refundPojo.getAllMoney(),refundPojo.getOrderNO());
			if(b){
				System.out.println("退款成功，退款金额="+refundPojo.getMoney()+",总退款金额="+refundPojo.getMoney()+",订单金额="+refundPojo.getAllMoney());
			}else{
				break;
			}
			upMoney(refundPojo.getUserId().toString(),String.valueOf(-refundPojo.getMoney()));
		}*/

    }
}